#include <iostream>
//#include "emis.h"
#include "tools.h"
#include "manager.h"

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

using namespace std;
using namespace MH;

void Tools::init_id(void)
{
	if(0 == access(ID_PATH,F_OK)) return;

	int fd = open(ID_PATH,O_WRONLY|O_CREAT|O_TRUNC,0644);
	if(0 > fd)
	{
		perror("open_init_id");
		return;
	}
	int id = 0;
	write(fd,&id,4);
	id = 10;
	write(fd,&id,4);
	id = 1000;
	write(fd,&id,4);

	close(fd);
}

int Tools::get_id(char m)
{
	int id_m=0,id_d=0,id_s=0;
	int id=0;
	int fd = open(ID_PATH,O_RDWR);
	if(0 > fd)
	{
		perror("open_get_id");
		return -1;
	}
	read(fd,&id_m,4);
	read(fd,&id_d,4);
	read(fd,&id_s,4);
	//printf("%d %d %d\n",id_m,id_d,id_s);
	switch(m)
	{
		case 1 : id = id_m++;break;
		case 2 : id = id_d++;break;
		case 3 : id = id_s++;break;
		default : break;
	}
	lseek(fd,SEEK_SET,0);
	//printf("%d %d %d\n",id_m,id_d,id_s);
	write(fd,&id_m,4);
	write(fd,&id_d,4);
	write(fd,&id_s,4);
	close(fd);
	return id;
}

int Tools::generator_MarId(void)
{
	return get_id(1);
}

int Tools::generator_DeptId(void)
{
	return get_id(2);
}

int Tools::generator_EmpId(void)
{
	return get_id(3);
}